2023/12/232087字符

Symbol 符号描述

特点

  • 没有字面量
  • 不能 new
  • 开发者通过精心设计,可以让属性无法通过常规方式访问到
Symbol('123') === Symbol('123');  //--> false

私有化变量

const people = (() => {
    const love = Symbol('love');
    return {
        name: 'bozai',
        age: 18,
        sex: 'boy',
        [love]: 'girl'  // 私有属性
    }
})();
Object.keys(people);  //--> ["name", "age", "sex"]
Object.getOwnPropertySymbols(people);  // 访问 Symbol 属性(只读)

共享

const love1 = Symbol.for();  // 创建一个 symbol 并放入全局中
const love2 = Symbol.for();
const boy1 = {
    [love1]: 'cuteGirl'
}
const boy2 = {
    [love2]: 'uniform'
}
love1 === love2  //--> true

知名符号

function Animal () {}
Object.defineProperty(Animal, Symbol.hasInstance, {
    value: function (dog) {
        console.log(`hello`)
    }
})
const dog = new Animal();
dog instanceof Animal  //--> true
Animal[Symbol.hasInstance](dog)  //--> true

isConcatSpreadable

const arr = [1, 2, 3];
const obj = {
    0: 'hello',
    1: 'cuteGirl',
    length: 2,  // 必须加 length 属性
    [Symbol.isConcatSpreadable]: true,
}
arr.concat(obj);  //-->  [1, 2, 3, "hello", "cuteGirl"]

toPrimitive

class Temperature {
    constructor (degree) {
        this.degree = degree;
    }
    [Symbol.toPrimitive](type) {
        // console.log(type)
        if (type === 'default') {
            return this.degree + '摄氏度';
        } else if (type === 'number') {
            return this.degree;
        } else if (type === 'string') {
            return this.degree + '℃';
        }
    }
}
let t = new Temperature(30);
t + '!'  //--> 30摄氏度!
t  //--> 30
String(t)  //--> 30℃

toStringTag

class Person {
    [Symbol.toStringTag] = 'Person'
}
const person = new Person();
Object.prototype.toString.apply(person);  //--> [object Person]